package com.ruoyi.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.framework.web.service.SysLoginService;
import com.ruoyi.common.framework.web.service.SysPermissionService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.kiam.AuthUtil;
import com.ruoyi.common.utils.kiam.KiamUtil;
import com.ruoyi.common.utils.kiam.OauthConfig;
import com.ruoyi.service.SysMenuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysMenuServiceImpl menuService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @Log(title = "登录")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(),loginBody.getUserType());
        return AjaxResult.success(MapUtil.builder().put("token",token).build()).put("token",token);
    }

    @PostMapping("/loginByCode")
    @Log(title = "登录")
    public Object loginByCode(String code)
    {
        // 生成令牌
        String APP_ID = "zhuanjiasmartCityAy";// "smartCityAy";// "zhuanjiasmartCityAy";//;
        String APP_KEY = "zhuanjiaSmartCitySecret";
        String serverUrl = KiamUtil.ossRestSever;

        OauthConfig.getOauthConfig().setMethod("oauth2.0");
        OauthConfig.getOauthConfig().setGetusrinfo("profile");
        AuthUtil authUtil = new AuthUtil();
        authUtil.setUrl(serverUrl);
        String token = authUtil.getToken("authorization_code", APP_ID, URLEncoder.encode( RuoYiConfig.getBackBasePath(), CharsetUtil.CHARSET_UTF_8), APP_KEY, code);
        if(token != null){
            JSONObject json = JSON.parseObject(token);
            String access_token = json.getString("access_token");
            String userinfo = authUtil.getUserInfo(access_token, APP_ID);
            JSONObject userJson = JSON.parseObject(userinfo);
            System.out.println("userinfo:" + userinfo);
            JSONObject userAttributes = userJson.getJSONObject("attributes");
            String userId = userAttributes.getString("USER_ID");
            System.out.println("userId:" + userId);
            return loginService.loginByKiamUserId(userId);
        }else{
            Map<Object, Object> rs = MapUtil.builder().put("token", "").put("msg", "登录失败").build();
            return rs;
        }
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        user = user.selectById();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
